<template>
  <div class="settlement-container">
    <c-model v-model="modelShow" width="590px" title="购物车结算">
      <span slot="footer"></span>
      <div class="settlement-list">
        <div class="thead">
          <div class="item name">商品</div>
          <div class="item price">单价</div>
          <div class="item number">数量</div>
          <div class="item total-price">金额</div>
        </div>
        <div class="tbody">
          <div class="row-item" v-for="(item, index) in list" :key="index">
            <div class="tr">
              <div class="item name">
                {{ item.name }}
                <label class="taste" v-if="item.skuNames">({{ item.skuNames }})</label>
                <div class="color-orange fz-12" v-if="item.isPackage">(套餐无法与优惠共享)</div>
              </div>
              <div class="item price">￥{{ item.price }}</div>
              <div class="item number">{{ item.number }}</div>
              <div class="item total-price">￥{{ item.totalPrice }}</div>
            </div>
            <div class="children" v-if="item.packageList.length">
              <div class="tr" v-for="(children, childrenIndex) in item.packageList" :key="childrenIndex">
                <div class="item name">{{ children.name }}</div>
                <div class="item price">￥{{ children.price }}</div>
                <div class="item number">{{ children.number }}</div>
                <div class="item total-price"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="sale">
        <div class="sale-bottom flex col-base row-end">
          <div class="total flex col-base">合计：<span class="price">{{ actualMoney }}</span></div>
        </div>
      </div>
      <div class="pay-list">
        <div class="item"
             :class="{'disabled': item.type == 4 && !canCardPay}"
             v-for="(item, index) of payWay"
             :key="index"
             @click="changePayType(item.type)"
        >
          <div class="pay-label">
            <div class="icon-check"
                 :class="{disabled: item.type == 4 && !canCardPay, checked: payType == item.type}"/>
            <img :src="require(`@/assets/images/shop/${item.icon}.png`)" alt="">{{ item.name }}
            <span class="color-red fz-12" v-if="item.type == 4 && !canCardPay">(购物车存在不支持会员卡支付商品)</span>
          </div>
        </div>
      </div>
      <div class="sale-remark">
        <i-input
          type="textarea"
          placeholder="请输入备注内容"
          size="small"
          v-model="remark"
          maxlength="100"
          show-word-limit
        ></i-input>
      </div>
      <div class="pay-footer flex row-center mt-20">
        <i-button type="primary" :loading="payLoading" @click.stop="submit()">确认支付</i-button>
      </div>
    </c-model>
    <!--扫码支付-->
    <scanPay v-model="qrcodeModel.is"
             :orderNumber="qrcodeModel.orderNumber"
             :qrcode="qrcodeModel.qrcode"
             :payType="qrcodeModel.payType"
             :money="actualMoney"
             :orderType="2"
             @success="paySuccess"
             @fail="payFail"/>
    <!--卡扣-->
    <payPassword v-model="pwdModalShow" :money="actualMoney" @confirm="createOrder"/>
    <!--选择优惠券-->
    <couponSelect v-model="couponModel.is"
                  :list="couponModel.list"
                  :source="couponModel.currType"
                  :selectId="(couponModel.item ? couponModel.item.couponId : null)"
                  @select="selectCoupon"/>
  </div>
</template>
<script>
import {createGoodsOrder, getCouponList, payOrder, refreshGoodsOrder} from "@/api/goods";
import {encryptByDESModeCBCUtf8to64} from "@/common/utils/des";
import scanPay from "@/components/scanPay/index.vue";
import payPassword from "@/components/payPassword/index.vue";
import couponSelect from "@/components/couponSelect/index.vue";
import {formatAmount} from "@/common/utils";
export default {
  name: "settlement",
  components: {
    scanPay,
    payPassword,
    couponSelect
  },
  data() {
    return {
      modelShow: false,
      list: [],
      remark: '',

      couponModel: {
        is: false,
        list: [],
        info: {},
        item: null,
        currType: null,
        couponMoney: 0
      },
      orderMoney: 0,
      actualMoney: 0,

      payWay: [
        {name: "微信支付", type: 5, icon: 'icon-wx', isDis: true},
        {name: "支付宝", type: 6, icon: 'icon-ali', isDis: true},
      ],
      canCardPay: false,
      payType: 5,
      payLoading: false,
      qrcodeModel: {
        is: false,
        qrcode: '',
        orderNumber: ''
      },
      pwdModalShow: false
    }
  },
  computed: {
    goodsList() {
      let list = this.list.map(element => {
        return {
          goodsId: element.id,
          goodsNum: element.number,
          goodNum: element.number,
          goodsPrice: element.price,
          tasteIds: element.skuIds,
          canCardPay: element.canCardPay,
          skuList: element.skuList,
          isPackage: element.isPackage,
          packageList: element.packageList
        };
      })
      return list
    },
  },
  methods: {
    settlementSku(skuInfo) {
      console.log(skuInfo)
      this.payType = 5
      this.list = [
        {
          id: skuInfo.goodsItem.id,
          imgUrl: skuInfo.goodsItem.imgUrl,
          name: skuInfo.goodsItem.name,
          price: skuInfo.price,
          totalPrice: skuInfo.totalPrice,
          otPrice: skuInfo.otPrice,
          otTotalPrice: skuInfo.otTotalPrice,
          number: skuInfo.number,
          skuNames: skuInfo.skuNames,
          canCardPay: skuInfo.goodsItem.canCardPay,
          isPackage: skuInfo.isPackage,
          skuIds: skuInfo.skuIds,
          skuList: skuInfo.skuList,
          packageList: skuInfo.packageList
        }
      ]
      this.collection()
    },
    settlementCart(cartInfo) {
      this.payType = 5
      this.list = cartInfo.list.map(item => {
        item.totalPrice = (item.price * item.number).toFixed(2)
        item.otTotalPrice = (item.otPrice * item.number).toFixed(2)
        return item
      })
      this.collection()
    },
    collection() {
      let params = {
        goodsList: this.goodsList,
        payType: this.payType,
        // version: '1.0.0'
      };
      getCouponList(params).then(res => {
        if (res.code != 200) {
          this.$Message.error(res.msg);
          return false
        }
        (res.data.couponList || []).map(item => {
          item.title = item.rate/10
          return item
        })
        this.modelShow = true;
        this.payLoading = false
        this.orderMoney = res.data.orderMoney
        this.actualMoney = res.data.actualMoney
        this.canCardPay = res.data.cardPay == 1
        this.couponModel = {
          is: false,
          info: res.data,
          item: null,
          currType: null,
          couponMoney: res.data.discounts,
          discountRate: parseFloat(res.data.discountRate)*10
        }
        this.remark = "";
      });
    },
    openCouponModal(type) {
      if (type == 1) {
        this.couponModel.list = this.couponModel.info.couponList;
        if (!this.couponModel.info.couponList.length) return
      } else {
        this.couponModel.list = this.couponModel.info.shopActivityList;
        if (!this.couponModel.info.shopActivityList.length) return
      }
      if (this.couponModel.currType != type) {
        this.couponModel.item = null
      }
      this.couponModel.currType = type
      this.couponModel.is = true
    },
    selectCoupon(item) {
      this.couponModel.item = item
      if (!item) {
        this.couponModel.couponMoney = 0
        this.couponModel.currType = null
      }
      this.refreshOrder()
    },
    changePayType(paytype) {
      this.payType = paytype
      // this.refreshOrder()
    },
    refreshOrder() {
      let params = {
        orderMoney: this.orderMoney,
        infoDTOList: this.goodsList,
        payType: this.payType,
        // version: '1.0.0'
      }
      if (this.couponModel.item) {
        params.couponId = this.couponModel.item.couponId;
        params.couponType = this.couponModel.currType;
      }
      refreshGoodsOrder(params).then(res => {
        if (res.code != 200) {
          this.$Message.error(res.msg || '获取订单信息失败');
          return
        }
        this.orderMoney = res.data.orderMoney;
        this.actualMoney = res.data.actualMoney;
        this.couponModel.couponMoney = res.data.discountMoney;
        this.totalPrice = res.data.actualMoney;
      });
    },

    submit() {
      if (this.payType == 4) {
        this.pwdModalShow = true;
      } else {
        this.createOrder();
      }
    },
    createOrder(password) {
      if (this.payLoading) return
      this.payLoading = true
      let params = {
        payType: this.payType,
        orderMoney: this.orderMoney,
        actualMoney: this.actualMoney, // 实付金额
        discountMoney: this.couponModel.couponMoney, // 优惠金额
        remark: this.remark || "",
        infoDTOList: this.goodsList,
        // version: '1.0.0'
      }
      if (this.couponModel.item) {
        params.couponType = this.couponModel.currType;
        params.couponId = this.couponModel.item.couponId;
      }
      if (this.payType == 4) {
        params.password = password;
      }
      console.log(params)
      createGoodsOrder({
        data: encryptByDESModeCBCUtf8to64(JSON.stringify(params))
      }).then(res => {
        if (res.code == 200) {
          this.payOrder({
            payType: this.payType,
            orderNumber: res.data.orderNumber,
            orderMoney: this.totalPrice
          })
          return false;
        }
        this.payLoading = false
        this.$Message.error(res.msg);
      }).catch(() => {
        this.payLoading = false
      });
    },
    payOrder(params) {
      payOrder({
        data: encryptByDESModeCBCUtf8to64(JSON.stringify(params))
      }).then(res => {
        if (res.code == 200) {
          if (params.payType == 4) {
            this.paySuccess();
          } else {
            this.qrcodeModel = {
              is: true,
              payType: params.payType,
              qrcode: res.data.imgUrl,
              orderNumber: params.orderNumber
            };
          }
          return false;
        }
        this.$Message.error(res.msg);
        this.payLoading = false;
      });
    },
    paySuccess() {
      this.$Message.success("支付成功");
      this.modelShow = false;
      this.payLoading = false;
      this.qrcodeModel.is = false
      this.$emit('success')
    },
    payFail() {
      this.payLoading = false;
    }
  }
}
</script>

<style  lang="scss">
@import "settlement.scss";
</style>
